import { ImclientService } from '@app/imclient';
import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import * as dayjs from 'dayjs';
import { FindOptionsWhere, MoreThan } from 'typeorm';
import WorkException from 'exception/work.exception';
import { Notice } from '@app/db/entity/Notice';
import PageDto from './dto/page.dto';

@Injectable()
export class NoticeService {
    constructor(
        private readonly imclient:ImclientService,
        private readonly db:DbService,
    ) {
        
    }

    public async send(id:number) {
        const sender_id = await this.db.sysConfig.selectValue('official_user', 'gonggao')
        if(!sender_id) throw new WorkException('请先设置公告账号')


        const row = await this.db.notice.findOne({id:id}, {title: true, content: true})

        const size = 90
        let lastId = 0

        const params = {
            sender_id: sender_id,
            message: {
                message_type: 0,
                text: JSON.stringify({t:row.title, c:row.content}),
            },
            sender_no_sense: true,
            attachment: {

            }
        }


        while(true) {
            const rows = await this.db.user.find(lastId == 0 ? null : {id: MoreThan(lastId)}, {imUserId:true, id:true, official: true}, 0, size)
            console.log(rows)
            const ids = []
            rows.forEach(row => {
                if(!row.official) {
                    ids.push(row.imUserId)
                }
            })
            if(ids.length > 0) {

                this.imclient.batchSendMessage({
                    ...params,
                    receiver_ids:ids
                })
            }

            if(rows.length < size) {
                break
            }else {
                lastId = rows[rows.length - 1].id
            }
        }
    }

    async page(dto:PageDto) {
        let result:PaginationResult<Notice> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<Notice> = {
           
        }




        result.total = await this.db.notice.count(where)

        if(result.total > 0) {

            result.rows = await this.db.notice.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})

            
        }

        return result
    }

    async add(dto:Notice) {
        return this.db.notice.insert({...dto, createTime : dayjs().unix()})
    }

    async update(dto:Notice) {
        let fields = Object.keys(dto) as (keyof Notice)[]
        if(fields.length == 0) return true

        const row = await this.db.notice.findOne({ id : dto.id })
        
        if(!row) return false

        let updateData:KeyToValueType<Notice> = {}

        for(let k in row) {
            if(k in dto) {
                if(row[k] == dto[k]) continue
    
                updateData[k] = dto[k]
            }
            
        }

        if(Object.keys(updateData).length == 0) return true

        updateData.updateTime = dayjs().unix()

        return this.db.notice.update({id : dto.id}, updateData)
    }

    async del(id:number) {
        let row = await this.db.notice.findOne({ id }, {id: true})
        if(!row) return
        return this.db.notice.delete({id : id})
    }
}
